package com.demo.tools;

import static com.bumptech.glide.load.DecodeFormat.PREFER_RGB_565;

import android.content.Context;

import androidx.annotation.NonNull;

import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.ExternalPreferredCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.request.RequestOptions;

//@GlideModule
public class MyAppGlideModule extends AppGlideModule {

    private static final int DISK_CACHE_SIZE = 1024 * 1024 * 100; // 100MB

    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        builder.setDefaultRequestOptions(getRequestOptions());
        builder.setMemoryCache(new LruResourceCache(getMemoryCacheSize(context)));
        builder.setBitmapPool(new LruBitmapPool(getBitmapPoolSize(context)));
        builder.setDiskCache(new ExternalPreferredCacheDiskCacheFactory(context, DISK_CACHE_SIZE));
    }

    private RequestOptions getRequestOptions() {
        RequestOptions options = new RequestOptions();
        options.format(PREFER_RGB_565);
        options.disallowHardwareConfig();
        return options;
    }

    private int getMemoryCacheSize(Context context) {
        MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context)
                .setMemoryCacheScreens(2)
                .build();
        return calculator.getBitmapPoolSize();
    }

    private int getBitmapPoolSize(Context context) {
        MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context)
                .setBitmapPoolScreens(1)
                .build();
        return calculator.getBitmapPoolSize();
    }
}
